package cn.sytton.taffe.file.service;

import cn.sytton.taffe.file.entity.FileEntity;
import cn.sytton.taffe.file.entity.FileGroupEntity;
import cn.sytton.taffe.file.mapper.FileGroupMapper;
import cn.sytton.taffe.file.mapper.FileMapper;
import cn.sytton.taffe.framework.util.ServletUtil;
import cn.sytton.taffe.framework.util.SpringContextUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.util.Assert;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.util.ArrayList;
import java.util.List;
import java.util.UUID;

/**
 * 文件服务抽象类
 *
 * @author skyrock
 */
public abstract class AbstractFileService implements InitializingBean {

    private String bucketName;
    private MinioService minioService;
    private FileMapper fileMapper;
    private final FileGroupMapper fileGroupMapper;

    public AbstractFileService() {
        minioService = SpringContextUtil.getBean("minioService");
        fileMapper = SpringContextUtil.getBean("fileMapper");
        fileGroupMapper = SpringContextUtil.getBean("fileGroupMapper");
    }

    /**
     * 上传文件
     * @param file file
     * @return 文件实体
     */
    public FileEntity upload(MultipartFile file) {
        return minioService.upload(file, bucketName);
    }

    /**
     * 上传文件
     * @param file
     * @return 文件实体
     */
    public FileEntity upload(File file) {
        return minioService.upload(file, bucketName);
    }

    /**
     * 上传文件并保存文件关系信息
     * @param file file
     * @return 文件实体
     */
    public FileEntity uploadAndSave(MultipartFile file) {
        FileEntity fileEntity = minioService.upload(file, bucketName);
        fileMapper.insert(fileEntity);
        return fileEntity;
    }

    /**
     * 上传多个文件并保存文件关系信息
     * @param files file
     * @return 文件组实体
     */
    public FileGroupEntity uploadAndSave(List<MultipartFile> files) {
        FileGroupEntity group = new FileGroupEntity();
        group.setFileGroupId(UUID.randomUUID().toString());
        for (MultipartFile file : files) {
            FileEntity fileEntity = minioService.upload(file, bucketName);
            fileMapper.insert(fileEntity);

            FileGroupEntity fileGroupEntity = new FileGroupEntity();
            fileGroupEntity.setFileGroupId(group.getFileGroupId());
            fileGroupEntity.setFileId(fileEntity.getFileId());
            fileGroupMapper.insert(fileGroupEntity);
            group.getFiles().add(fileEntity);
        }
        return group;
    }

    /**
     * 下载文件
     * @param fileId 文件ID
     */
    public void download(String fileId) {
        FileEntity file = fileMapper.selectById(fileId);
        minioService.download(file, ServletUtil.getResponse());
    }

    /**
     * 下载文件组压缩包
     * @param groupId 文件组ID
     */
    public void downloadGroup(String groupId, String name) {
        List<FileEntity> files = new ArrayList<>();
        List<FileGroupEntity> group = fileGroupMapper
                .selectList(new LambdaQueryWrapper<FileGroupEntity>()
                .eq(FileGroupEntity::getFileGroupId, groupId));
        for(FileGroupEntity fg : group) {
            FileEntity file = fileMapper.selectById(fg.getFileId());
            files.add(file);
        }
        if (files.size() > 0) {
            if (files.size() == 1) {
                minioService.download(files.get(0), ServletUtil.getResponse());
            } else {
                minioService.downloadZip(files, ServletUtil.getResponse(), name);
            }
        }
    }

    /**
     * 下载文件
     * @param objectName
     * @param bucketName
     */
    protected void downloadObject(String bucketName, String objectName) {
        minioService.download(bucketName, objectName, ServletUtil.getResponse());
    }

    /**
     * 下载文件
     * @param objectName
     */
    public void downloadObject(String objectName) {
        minioService.download(bucketName, objectName, ServletUtil.getResponse());
    }

    /**
     * 删除文件并删除关系记录
     * @param fileId
     */
    public void deleteFile(String fileId) {
        FileEntity file = fileMapper.selectById(fileId);
        minioService.removeObjects(file.getBucketName(), file.getObjectName());
        fileMapper.deleteById(fileId);
    }

    /**
     * 获取永久文件访问链接，(如果bucketName是private的，永久链接无法访问)
     * @param fileId 文件ID
     * @return
     */
    public String getPublicUrl(String fileId) {
        FileEntity file = fileMapper.selectById(fileId);
        return minioService.getPublicUrl(file.getObjectName(), file.getBucketName());
    }

    /**
     * 获取资源临时访问链接, 默认24小时过期
     * @param fileId 文件ID
     * @return
     */
    public String getUrl(String fileId) {
        FileEntity file = fileMapper.selectById(fileId);
        return minioService.getUrl(file.getObjectName(), file.getBucketName());
    }

    /**
     * 获取资源临时访问链接
     * @param fileId 文件ID
     * @param expiryMinute 有效期单位分钟
     * @return
     */
    public String getUrl(String fileId, long expiryMinute) {
        FileEntity file = fileMapper.selectById(fileId);
        return minioService.getUrl(file.getObjectName(), file.getBucketName(), expiryMinute);
    }

    /**
     * 判断并创建private存储桶
     */
    public void makeBucket() {
        if (!minioService.bucketExists(this.bucketName)) {
            minioService.makeBucket(this.bucketName);
        }
    }

    /**
     * 判断并创建Public存储桶
     */
    public void makePublicBucket() {
        if (!minioService.bucketExists(this.bucketName)) {
            minioService.makePublicBucket(this.bucketName);
        }
    }

    public void setBucketName(String bucketName) {
        this.bucketName = bucketName;
    }
    public void setMinioService(MinioService minioService) {
        this.minioService = minioService;
    }
    public void setFileMapper(FileMapper fileMapper) {
        this.fileMapper = fileMapper;
    }

    @Override
    public void afterPropertiesSet() throws Exception {
        Assert.notNull(bucketName, "bucketName must be set");
    }
}
